package controller;

import java.io.IOException;
import java.math.BigInteger;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import javax.servlet.http.HttpSession;

import user.User;
import utils.StatesEnum;

public class LoginController extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	public void process ( HttpServletRequest request, HttpServletResponse response ) {
		ServletContext context;
		RequestDispatcher dispatcher;
		UserManager um = UserManager.getInstance();
		HttpSession session;
		
		context = getServletContext();
		session = request.getSession();
		
		String error = null;
		String dispatcherTarget = "/error.jsp";				
		context = getServletContext();
			
		User curUser = (User) (session.getAttribute("user"));
		
		if(curUser != null) {
			if(request.getParameterNames() != null)
	        {		
				User testusr = new User();
				String username = request.getParameter("username");
				String password = request.getParameter("password");
				String token = request.getParameter("token");
				BigInteger generatedToken = BigInteger.valueOf(Long.getLong(token)); // ???
				testusr.setUsername(username);
				testusr.setPassword(password);
				testusr.setGeneratedToken(generatedToken);
				
				StatesEnum state = StatesEnum.s50; // Testen ob der Nutzer schon zu 50% angemeldet ist
				if(um.isUserLoggedInWithState(testusr, state) == true){
					//Jetzt Token vergleichen
					if(um.checkUserToken(testusr) == true){
						// User ist jetzt 100% angemeldet
						um.updateUserState(testusr, StatesEnum.s100);
						dispatcherTarget = "/success.jsp";						
					}
					else {
						dispatcherTarget = "/error.jsp";	
					}
				}
				else {
					dispatcherTarget = "/error.jsp";
				}				
			}
			else
			{
				dispatcherTarget = "/error.jsp";
			}
			
			if (error != null && !error.isEmpty())
				request.setAttribute("errorMessage", error);
			
			dispatcher = context.getRequestDispatcher(dispatcherTarget);
					
			try {
				dispatcher.forward(request, response);
			} 
			catch (ServletException e) {
				e.printStackTrace();
				
			} 
			catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	public void doGet ( HttpServletRequest request, HttpServletResponse response ) {
		process(request, response);
	}
	
	public void doPost ( HttpServletRequest request, HttpServletResponse response ) {
		process(request, response);
	}
}


